const express = require('express');
const router = express.Router();
const sqlFn = require('./config');
const jwt = require('jsonwebtoken');
const jwtSecret = require('./jwtSecret');
const url = require('url');
const fs = require('fs');
const  multer = require('multer');
/**
 * 登录接口
 */
router.post('/login', (req, res) => {
    const username = req.body.username;
    const password = req.body.password;
    const sql = 'select * from user where username=? and password=?';
    const arr = [username, password];
    sqlFn(sql, arr, result => {
        if( result.length > 0) {
            const token = jwt.sign({
                id: result[0].id,
                username: result[0].username
            },jwtSecret.jwtSecret)
            res.send({
                token,
                code: 200,
                msg: '认证成功'
            })
        }else {
            res.send({
                msg: '用户名或密码错误'
            })
        }
    })
})
/**
 * 注册接口
 */
router.post('/register', (req,res) => {
    const username = req.body.username;
    const password = req.body.password;
    const email = req.body.email;
    const userSql = 'select * from user where username=?';
    sqlFn(userSql,[username], result => {
        console.log(result.length);
        if(result.length > 0) {
            res.send({
                msg: '该账号已存在'
            })
        }else {
            const sql = 'insert into user values(null, ?, ?, ?)';
            const arr = [username, password, email];
            sqlFn(sql, arr, result => {
                if(result.affectedRows > 0) {
                    res.send({
                        msg: '注册成功'
                    })
                }else {
                    res.send({
                        msg: '注册失败'
                    })
                }
            })
        }
    })

})

/**
 * 产品列表数据读取
 */
router.get('/backend/item/selectTabItemAllByPage', (req, res) => {
    let page = url.parse(req.url, true).query.page || 1;
    const sql = "select * from project order by id desc limit 10 offset " + (page - 1) * 10
    sqlFn(sql, null, result => {
        if(result.length > 0) {
            res.send({
                code: 200,
                result,
                msg: '读取数据成功'
            })
        }else {
            res.send({
                msg: '读取数据失败'
            })
        }
    })
})
/**
 * 商品总页数
 */
router.get('/total', (req, res) => {
    const sql = 'select count(*) from project where id';
    sqlFn(sql, null, result => {
        if(result.length > 0) {
            res.send({
                code: 200,
                result,
                msg: '请求成功'
            })
        }else {
            res.send({
                msg: '请求失败'
            })
        }
    })
})
/**
 * 商品模糊查询
 */
router.get('/search', (req, res) => {
    const search = url.parse(req.url, true).query.search;
    const sql = "select * from project where concat(`title`,`sellPoint`,`descs`) like '%" + search + "%'";
    sqlFn(sql, null, result => {
        if(result.length > 0) {
            res.send({
                code: 200,
                result,
                msg: '请求成功'
            })
        }else {
            res.send({
                msg: '请求失败'
            })
        }
    })
})
/**
 * 类目选择
 */
router.get('/bankend/itemCategory/selectItemCategoryByParentId', (req, res) => {
    const id = url.parse(req.url, true).query.id || 1;
    const sql = 'select * from category where id=?';
    const arr = [id];
    sqlFn(sql, arr, (result) => {
        if(result.length > 0) {
            res.send({
                code: 200,
                result,
                msg: '请求成功'
            })
        }else {
            res.send({
                msg: '请求失败'
            })
        }
    })
})
/**
 * 类目名称获取
 */
router.get('/bankend/itemCategory/selectItemCategoryByParentCId', (req, res) => {
    const cid = url.parse(req.url, true).query.cid;
    const sql = 'select * from category where cid=?';
    const arr = [cid];
    sqlFn(sql, arr, (result) => {
        if(result.length > 0) {
            res.send({
                code: 200,
                result,
                msg: '请求成功'
            })
        }else {
            res.send({
                msg: '请求失败'
            })
        }
    })
})
/**
 * 上传图片
 */
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, "./server/upload/")
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + "-" + file.originalname)
    }
})

var createFolder = function (folder) {
    try {
        fs.accessSync(folder);
    } catch (e) {
        fs.mkdirSync(folder);
    }
}
var uploadFolder = './server/upload/';
createFolder(uploadFolder);
var upload = multer({ storage: storage });

router.post('/upload', upload.single('file'), function (req, res, next) {
    var file = req.file;
    console.log('文件类型：%s', file.mimetype);
    console.log('原始文件名：%s', file.originalname);
    console.log('文件大小：%s', file.size);
    console.log('文件保存路径：%s', file.path);
    res.json({ res_code: '0', name: file.originalname, url: file.path });
});
/**
 * 添加商品数据
 */
router.get("/backend/item/insertTbItem", (req, res) => {
    var title = url.parse(req.url, true).query.title || "";
    var cid = url.parse(req.url, true).query.cid || "";
    var sellPoint = url.parse(req.url, true).query.sellPoint || "";
    var price = url.parse(req.url, true).query.price || "";
    var num = url.parse(req.url, true).query.num || "";
    var desc = url.parse(req.url, true).query.desc || "";
    var image = url.parse(req.url, true).query.image || "";
    const sql = "insert into project values (null,?,?,?,?,?,?,'',1,'','',?)";
    var arr = [title, image, sellPoint, price, cid, num, desc];
    sqlFn(sql, arr, result => {
        if (result.affectedRows > 0) {
            res.send({
                code: 200,
                msg: "添加成功"
            })
        } else {
            res.send({
                code: 500,
                msg: "添加失败"
            })
        }
    })
})
/**
 * 删除商品
 */
router.get("/backend/item/deleteItemById", (req, res) => {
    let id = url.parse(req.url, true).query.id;
    let sql = "delete from project where id=?";
    let arr = [id];
    sqlFn(sql, arr, (result) => {
        if(result.affectedRows > 0) {
            res.send({
                code:200,
                msg: "删除成功"
            })
        }else {
            res.send({
                code: 500,
                msg: "删除失败"
            })
        }
    })
})
/**
 * 预更新
 */
router.get("/backend/item/preUpdateItem", (req, res) => {
    var id = url.parse(req.url, true).query.id;
    const sql = "select * from project where id=?";
    sqlFn(sql, [id], result => {
        if (result.length > 0) {
            res.send({
                status: 200,
                result
            })
        } else {
            res.send({
                status: 500,
                msg: "预更新失败"
            })
        }
    })
})
/**
 * 修改接口
 */
router.get("/backend/item/updateTbItem", (req, res) => {
    var id = url.parse(req.url, true).query.id;
    var title = url.parse(req.url, true).query.title || "";
    var sellPoint = url.parse(req.url, true).query.sellPoint || "";
    var price = url.parse(req.url, true).query.price || "";
    var num = url.parse(req.url, true).query.num || "";
    var desc = url.parse(req.url, true).query.desc || "";
    var image = url.parse(req.url, true).query.image || "";
    var cid = url.parse(req.url, true).query.cid;
    var sql = "update project set title=?,sellPoint=?,cid=?,price=?,num=?,descs=?,image=? where id=?";
    var arr = [title, sellPoint, cid, price, num, desc, image, id];
    sqlFn(sql, arr, result => {
        if (result.affectedRows > 0) {
            res.send({
                status: 200,
                msg: "修改成功"
            })
        } else {
            res.send({
                status: 500,
                msg: "修改失败"
            })
        }
    })
})
/**
 * 规格参数读取
 */
router.get('/backend/itemParam/selectItemParamAll', (req, res) => {
    let page = url.parse(req.url, true).query.page || 1;
    const sql = "select * from params order by id desc limit 10 offset " + (page - 1) * 10
    sqlFn(sql, null, result => {
        if(result.length > 0) {
            res.send({
                status: 200,
                result
            })
        }else {
            res.send({
                status: 500,
                msg: '读取数据失败'
            })
        }
    })
})
/**
 * 规格参数模糊查询
 */
router.get('/paramsSearch', (req, res) => {
    const search = url.parse(req.url, true).query.search;
    const sql = "select * from params where concat(`id`,`itemCatId`,`paramData`) like '%" + search + "%'";
    sqlFn(sql, null, result => {
        if(result.length > 0) {
            res.send({
                code: 200,
                result,
                msg: '请求成功'
            })
        }else {
            res.send({
                msg: '请求失败'
            })
        }
    })
})
/**
 * 添加规格参数
 */
router.get("/backend/itemParam/insertItemParam", (req, res) => {
    let itemCatId = url.parse(req.url, true).query.itemCatId;
    let paramsContent = url.parse(req.url, true).query.content;
    const sql = "insert into params values (null,?,?)";
    sqlFn(sql, [itemCatId, paramsContent], result => {
        if(result.affectedRows > 0) {
            res.send({
                status: 200,
                msg: '添加成功'
            })
        }else {
            res.send({
                status: 500,
                msg: '添加失败'
            })
        }
    })
})
/**
 * 删除规格参数
 */
router.get('/params/delete', (req, res) => {
    let id = url.parse(req.url, true).query.id;
    const sql = "delete from params where id=?"
    sqlFn(sql, [id], result => {
        if(result.affectedRows >0) {
            res.send({
                status: 200,
                msg: '删除成功'
            })
        }else {
            res.send({
                status: 500,
                msg: '删除失败'
            })
        }
    })
})
/**
 * 查询规格参数-商品管理
 */
router.get("/product/params/paramsItem", (req, res) => {
    let cid = url.parse(req.url, true).query.cid;
    const sql = "select * from params where itemCatId=?";
    sqlFn(sql, [cid], result => {
        if(result.length > 0) {
            res.send({
                status: 200,
                result
            })
        }else {
            res.send({
                status: 500,
                msg: '无更多数据'
            })
        }
    })
})
/**
 * 规格参数总页数
 */
router.get('/paramsTotal', (req, res) => {
    const sql = 'select count(*) from params where id';
    sqlFn(sql, null, result => {
        if(result.length > 0) {
            res.send({
                code: 200,
                result,
                msg: '请求成功'
            })
        }else {
            res.send({
                msg: '请求失败'
            })
        }
    })
})
/**
 * 内容分类管理-导航
 */
router.get("/content/selectContentCategoryByParentId", (req, res) => {
    const id = url.parse(req.url, true).query.id || 1;
    const sql = "select * from content where id=?";
    sqlFn(sql, [id], result => {
        if(result.length > 0) {
            res.send({
                status: 200,
                result
            })
        }else {
            res.send({
                status: 500,
                msg: '暂无数据'
            })
        }
    })
})
/**
 * 内容分类管理-导航-添加
 */
router.get("/content/insertContentCategory", (req, res) => {
    const pid = url.parse(req.url, true).query.pid;
    const name = url.parse(req.url, true).query.name;
    const currentId = Math.floor(Math.random() * 10000);
    const sql = "insert into content values (?, ?, ?)";
    sqlFn(sql, [pid, name, currentId], result => {
        if(result.affectedRows > 0) {
            res.send({
                status: 200,
                msg: "添加成功"
            })
        }else {
            res.send({
                status: 500,
                msg: "添加失败"
            })
        }
    })

})
/**
 * 内容分类管理-导航-删除
 */
router.get('/content/deleteContentCategory', (req, res) => {
    let pid = url.parse(req.url, true).query.pid;
    const sql = "delete from content where pid=?"
    sqlFn(sql, [pid], result => {
        if(result.affectedRows >0) {
            res.send({
                status: 200,
                msg: '删除成功'
            })
        }else {
            res.send({
                status: 500,
                msg: '删除失败'
            })
        }
    })
})
/**
 * 内容分类管理-列表-查询
 */
router.get("/content/selectTabContentAllByCategoryId", (req, res) => {
    const pid = url.parse(req.url, true).query.pid;
    const sql = "select * from contentinfo where pid=?";
    sqlFn(sql, [pid], result => {
        if(result.length > 0) {
            res.send({
                status: 200,
                result
            })
        }else {
            res.send({
                status: 500,
                msg: "暂无数据"
            })
        }
    })
})
module.exports = router;